package idx;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer; 
public class Builder {
	public static void main(String [] args) throws Exception
	{
		Builder b = new Builder(args[0], args[1]);
		b.BuildIdx();
		//File a = new File("tc");
		//File b = new File("shit");
		//a.renameTo(b);
		return;
	}
	String idxPath;
	String buildPath;
	Builder(String i, String b) throws IOException
	{
		idxPath = i;
		buildPath = b;
		//ex = new Extractor();
		//ex.buildConvertTable("table.txt");
	}
	//Extractor ex;
	void BuildIdx() throws Exception
	{
	    Analyzer analyzer = new IKAnalyzer(); 
	    // 1. create the index
	    //Directory index = new RAMDirectory();
	    FSDirectory index = FSDirectory.open(new File(idxPath));

	    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34, analyzer);

	    IndexWriter idxWriter = new IndexWriter(index, config);
	    
	    //2. find the files(recursive)
	    recursiveAdd(buildPath, idxWriter);
	    idxWriter.optimize();
	    idxWriter.close();
		return;
	}
	void recursiveAdd(String path, IndexWriter w) throws CorruptIndexException, IOException
	{
		File f = new File(path);
		File sub[] = f.listFiles();
		for(int i = 0; i < sub.length; i++)
		{
			//System.out.println(ex.Convert(sub[i].getAbsolutePath()).substring(28));
			if(sub[i].isDirectory())
				recursiveAdd(sub[i].getAbsolutePath(), w);
			else
			{
				if(!sub[i].getName().endsWith(".ext") || sub[i].getName().startsWith("Category") || sub[i].getName().startsWith("Talk")
						|| sub[i].getName().startsWith("User") || sub[i].getName().startsWith("Template"))
					continue;
				Document doc = new Document();
				//File n = new File(ex.Convert(sub[i].getAbsolutePath()).substring(28));
				//System.out.println(sub[i].getName());
				doc.add(new Field("title",sub[i].getName(),Field.Store.YES, Field.Index.ANALYZED));
				doc.add(new Field("path", sub[i].getAbsolutePath(), Field.Store.YES, Field.Index.ANALYZED));
				doc.add(new Field("context", new FileReader(sub[i])));
				w.addDocument(doc);
			}
		}
		return;
	}
}
